package com.iflytek.sbd.demo.yinyong;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @program: sbd
 * @description: 弱引用demo
 * @author: 陈英俊
 * @create: 2022-01-26 11:04
 */
public class WeakReferenceDemo {

    public static int M = 1024*1024;

    public static void printlnMemory(String tag){
        Runtime runtime = Runtime.getRuntime();
        int M = WeakReferenceDemo.M;
        System.out.println("\n"+tag+":");
        System.out.println(runtime.freeMemory()/M+"M(free)/" + runtime.totalMemory()/M+"M(total)");
    }

    public static void main(String[] args){

        ReferenceQueue<Object> weakReferenceQueue = new ReferenceQueue<>();

        WeakReferenceDemo.printlnMemory("1.原可用内存和总内存");

        //创建弱引用
        WeakReference<Object> weakRerference = new WeakReference<Object>(new byte[10*WeakReferenceDemo.M],weakReferenceQueue);
        WeakReferenceDemo.printlnMemory("2.实例化10M的数组,并建立弱引用");
        System.out.println("weakRerference.get() : "+weakRerference.get());
     //   System.out.println("weakReferenceQueue关联队列:"+weakReferenceQueue.poll());

        System.gc();
        WeakReferenceDemo.printlnMemory("3.GC后");
        System.out.println("weakRerference.get() : "+weakRerference.get());
      //  System.out.println("weakReferenceQueue关联队列:"+weakReferenceQueue.poll());
    }
}
